package wxapp

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/dao"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/apiin"
	"hotgo/internal/model/input/sysin"
	"math/rand"
	"time"
)

// ActivityList 视频下载首页列表
func (s *sWxapp) ActivityList(ctx context.Context, page int, pageSize int) (list *[]sysin.ActivityListModel, totalCount int, err error) {
	totalCount, err = dao.Activity.Ctx(ctx).Page(page, pageSize).OrderDesc("id").Count()
	if err != nil {
		return
	}
	res, err := dao.Activity.Ctx(ctx).Page(page, pageSize).OrderDesc("id").All()
	if err != nil {
		return
	}
	err = gconv.Structs(res, &list)
	return
}

// ActivityDetail 活动详情
func (s *sWxapp) ActivityDetail(ctx context.Context, id int) (data entity.Activity, err error) {
	res, err := dao.Activity.Ctx(ctx).Where(g.Map{"id": id}).One()
	if err != nil {
		return
	}
	if res.IsEmpty() {
		err = gerror.New("活动id不存在")
		return
	}
	err = gconv.Struct(res, &data)
	return
}

// GetVideo 获取下载视频
func (s *sWxapp) GetVideo(ctx context.Context, activityId int, idCard string) (list []apiin.GetVideo, err error) {
	user, err := dao.ActivityUser.Ctx(ctx).Where(g.Map{"activity_id": activityId, "id_card": idCard}).One()
	if err != nil {
		return
	}
	activity, err := dao.Activity.Ctx(ctx).Where(g.Map{"id": activityId}).One()
	if err != nil {
		return
	}
	if user.IsEmpty() {
		err = gerror.New("用户不存在！")
		return
	}
	list = []apiin.GetVideo{}
	videos, err := dao.UserVideo.Ctx(ctx).Where(g.Map{"uid": user["id"]}).OrderDesc("id").All()
	if err != nil {
		return
	}
	err = gconv.Structs(videos, &list)
	if err != nil {
		return
	}
	for k, _ := range list {
		list[k].Name = gconv.String(user["name"])
		list[k].Price = gconv.Float64(activity["price"])
	}
	return
}

// CreateOrder 订单创建
func (s *sWxapp) CreateOrder(ctx context.Context, videoId int) (orderId int64, orderNum string, err error) {
	video, err := dao.UserVideo.Ctx(ctx).Where(g.Map{"id": videoId}).OrderDesc("id").One()
	if err != nil {
		return
	}
	activity, err := dao.Activity.Ctx(ctx).Where(g.Map{"id": video["activity_id"]}).One()
	if err != nil {
		return
	}
	if activity.IsEmpty() {
		err = gerror.New("活动不存在")
		return
	}
	record, err := dao.VideoOrder.Ctx(ctx).Where(g.Map{"video_id": videoId, "status": 1}).All()
	if err != nil {
		return
	}
	if len(record) != 0 {
		err = gerror.New("请勿重复购买！")
		return
	}
	data := entity.VideoOrder{}
	openId := ctx.Value("openid").(string)
	prefix := "WX"
	timestamp := time.Now().Format("20060102150405")
	random := fmt.Sprintf("%06d", rand.Intn(999999))
	data.OrderNum = fmt.Sprintf("%s%s%s", prefix, timestamp, random)
	data.OpenId = openId
	data.ActivityId = gconv.Int(video["activity_id"])
	data.VideoId = videoId
	data.Price = gconv.Float64(activity["price"])
	res, err := dao.VideoOrder.Ctx(ctx).Insert(data)
	if err != nil {
		return
	}
	orderId, err = res.LastInsertId()
	orderNum = data.OrderNum
	return
}
